<template>
  <div class="rs-code-mirror">
    <div class="rs-code-mirror-box">
      <textarea ref="textarea"></textarea>
    </div>
  </div>
</template>
<script>
import CodeMirror from 'codemirror/lib/codemirror'
import './codemirror';

export default {
  name: 'rsCodemirror',
  data(){
    return {
      codeMirror: null,
      code: '',
      showThemeSelect: false
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: ''
    },
    theme: {
      type: String,
      default: 'mdn-like'
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    option: {
      type: Object,
      default: function() {
        return null
      }
    }
  },
  watch: {
    value(val , oldVal){
      if(val !== this.code){
        this.codeMirror && this.codeMirror.setValue(this.value);
      }
    },
    mode(val, oldVal){
      this.updateOption('mode' , val);
    },
    readOnly(val , oldVal){
      this.updateOption('readOnly' , val);
    },
    theme(val , oldVal){
      this.updateOption('theme' , val);
    },
    option: {
      deep: true,
      handler: function(val, oldVal){
        this.updateOption(val);
      }
    }
  },
  mounted(){
    this.codeMirror = CodeMirror.fromTextArea(this.$refs.textarea , Object.assign({
      mode: this.mode,
      theme: this.theme,
      lineNumbers: true,
      readOnly: this.readOnly,
      foldGutter: true,
      gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers']
    } , this.option));

    this.codeMirror.on('change' , (coder) => {
      this.code = coder.getValue();
      if(this.code !== this.value){
        this.$emit('input', this.code);
        this.$emit('change' , this.code);
      }
    })
    this.codeMirror.setValue(this.value);
  },
  methods: {
    updateOption(option , value){
      if(this.codeMirror && this.codeMirror.setOption && option){
        let opts = {};
        if(typeof option === 'string'){
          opts[option] = value;
        }
        if(typeof option === 'object'){
          opts = option;
        }
        Object.keys(opts).forEach(
          name => {
            this.codeMirror.setOption(name , opts[name]);
          }
        )
      }
    }
  }
}
</script>
<style lang="scss">
.rs-code-mirror {
  width: 100%;
  position: relative;
  z-index: 0;
  min-height: 72px;
  display: flex;
  >.rs-code-mirror-box{
    flex: 1;
    width: 100%;
    height: auto;
    max-height: 100%;
  }
  .CodeMirror {
    height:100% !important;
    // min-height: 72px;
  }
  .CodeMirror-scroll {
    height:100%;
    // min-height: 72px;
    // overflow-y: hidden;
    // overflow-x: auto;
  }
}
</style>